package com.zyg.apart.filter;

import com.zyg.apart.model.User;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * 过滤
 */
@Component
@ConfigurationProperties(prefix = "system")
public class ApartFilter implements Filter {

    //白名单
    private List<String> whitelist;

    public List<String> getWhitelist() {
        return whitelist;
    }

    public void setWhitelist(List<String> whitelist) {
        this.whitelist = whitelist;
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //是否是白名单，是则通过
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String uri=request.getRequestURI();
        for (String str:whitelist) {
            if (uri.matches(str)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //不是白名单，则转入登录
        User user= (User) request.getSession().getAttribute("u");
        if (user != null){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        request.getRequestDispatcher("/login/lgPage").forward(servletRequest,servletResponse);
    }
}
